﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
using System.Runtime.InteropServices.WindowsRuntime;

namespace KinectMetroApp.KinectDetection
{
    public class Client
    {
        private static object consoleLock = new object();
        private const int sendChunkSize = 64;
        private const int receiveChunkSize = 256;
        private const bool verbose = true;
        private static readonly TimeSpan delay = TimeSpan.FromMilliseconds(1000);


        private static StreamWebSocket WebSocket { get; set; }

        public static async Task Connect(string uri,string msg)
        {
            WebSocket = null;

            try
            {

                WebSocket = new StreamWebSocket();
                await WebSocket.ConnectAsync(new Uri(uri));
                await Send(WebSocket, msg);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: {0}", ex);
            }
            finally
            {
                if (WebSocket != null)
                    WebSocket.Close(3000, "Close");
                Console.WriteLine();
                Console.WriteLine("WebSocket closed.");
            }
        }

        private static async Task Send(StreamWebSocket webSocket, string msg)
        {

            byte[] buffer = Encoding.UTF8.GetBytes(msg);


            await webSocket.OutputStream.WriteAsync(buffer.AsBuffer());
            LogStatus(false, buffer);

            if (delay > TimeSpan.Zero)
                await Task.Delay(delay);
        }

        private static async Task Receive(StreamWebSocket webSocket)
        {
            byte[] buffer = new byte[receiveChunkSize];

            while (true)
            {
                try
                {
                    IBuffer b = buffer.AsBuffer();
                    await webSocket.InputStream.ReadAsync(b, b.Length, InputStreamOptions.Partial);
                    LogStatus(true, buffer);
                }
                catch (Exception)
                {

                    throw;
                }
            }
        }

        private static void LogStatus(bool receiving, byte[] buffer)
        {
            lock (consoleLock)
            {
                Console.ForegroundColor = receiving ? ConsoleColor.Green : ConsoleColor.Gray;
                Console.WriteLine("{0} {1} bytes... ", receiving ? "Received" : "Sent", buffer.Length);

                if (verbose)
                {
                    Console.WriteLine(BitConverter.ToString(buffer));
                    Console.WriteLine(Encoding.UTF8.GetString(buffer));
                }

                Console.ResetColor();
            }
        }
    }
}
